import env from './env.js';
import store from '../store/store.js'; // 导入 Vuex Store

//心跳间隔，单位毫秒
let heartBeatDelay = 10000
let heartBeatInterval = null

let reconnectInterval = null

//重连间隔，单位毫秒
let reconnectTimes = 10000

let msg = {}

let socketTask = null

//封装的对象，最后以模块化向外暴露，
//init方法 初始化socketTask对象
//completeClose方法 完全将socketTask关闭（不重连）
//其他关于socketTask的方法与uniapp的socketTask api一致
let ws = {
	isErrorTriggered: false,
	socketTask: null,
	isUserClose: false,
	init,
	send,
	completeClose
}

function init() {
	//连接
	socketTask = uni.connectSocket({
		// url: 'ws://47.107.238.6:9325/?token=' + store.getters['m_user/getToken'],
		// url: 'ws://app.dezhoucloud.com:9325/?token=' + store.getters['m_user/getToken'],
		// url: 'wss://app.dezhoucloud.com:9325/?token=' + store.getters['m_user/getToken'],
		// url: 'wss://app.dezhoucloud.com:9325/?token=' + store.getters['m_user/getToken'],
		/*  */
		url: 'ws://192.168.3.90:9325/?token=' + store.getters['m_user/getToken'],
		// /*  */
		// url: 'wss://app.dezhoucloud.com/wss/?token=' + store.getters['m_user/getToken'],
		success: () => {
			console.log("创建连接成功");
		},
		complete: () => { },
		fail: (e) => {
			store.state.isOpenSocket = false
		},
	});

	socketTask.onError((res) => {
		console.log(res, "WebSocket连接错误");
		store.state.isOpenSocket = false;
		if (!ws.isErrorTriggered) {
			ws.isErrorTriggered = true;
			reconnect();
		}
	});

	socketTask.onOpen((res) => {
		store.state.isOpenSocket = true;
		//先将心跳与重连的定时器清除
		clearInterval(heartBeatInterval)
		clearInterval(reconnectInterval)

		heartBeat();
	});
	socketTask.onMessage((res) => {
		const data = JSON.parse(res.data);
		switch (data.code) {
			case "0":
				console.log(data, 'webSocket连接正常')
				break;
			case "1":
				console.log(data.message, "sssss")
			// for (var obj in data.message) {
			// 	store.commit("m_message/saveOffMessageStorage", {
			// 		data: data.message[obj],
			// 		index: obj
			// 	});
			// }
			// msg.code = "3";
			// send(JSON.stringify(msg))
			// break;
			/*  */
			case "2":
				let message = {}
				if (data.message.messageType == '0') {
					message = {
						'friendId': data.message.fromId,
						'message': {
							/* 问政订单id */
							'consultationOrderId': data.message.consultationOrderId,
							/*  */
							'content': data.message.content,
							'createTime': data.message.createTime,
							'fromId': data.message.fromId,
							'messageId': data.message.messageId,
							'toId': data.message.toId,
							"unickname": data.message.unickname,
							"avatar": data.message.avatar,
							'readStatus': data.message.readStatus,
							'messageType': data.message.messageType,
							'type': data.message.type,
							'isUemployee': data.message.isUemployee,
							'second': data.message.second,
							'isRetract': false
						}
					}
				} else if (data.message.messageType == '1') {
					message = {
						'groupId': data.message.groupId,
						'message': {
							'content': data.message.content,
							'createTime': data.message.createTime,
							'fromId': data.message.fromId,
							"avatar": data.message.avatar,
							"unickname": data.message.unickname,
							"groupAvatar": data.message.groupAvatar,
							"groupName": data.message.groupName,
							'messageId': data.message.messageId,
							'readStatus': data.message.readStatus,
							'messageType': data.message.messageType,
							'type': data.message.type,
							'second': data.message.second,
							'isRetract': false
						}
					}
					if (data.message.fromId == uni.getStorageSync("ID")) {
						return;
					}
				}
				/* 创建会话 */
				saveMessage(message);
				break;
			/* 已读 未读 */
			case "4":
				return;
				if (data.data) {
					store.commit("m_message/UPDATE_STATUS", data.message.message.messageId);
				}
				break;
			//撤回指令6在线，7离线
			case "6":
				return;
				store.commit("m_message/RETRACT_MESSAGE", data.message)
				break;
			/* 是否撤回 */
			case "7":
				return;
				for (var obj in data.message) {
					store.commit("m_message/RETRACT_OFF_MESSAGE", {
						data: data.message[obj],
						index: obj
					});
				}
				break
			case "8":
				console.log("haoyou")
				break;
			case "9":
				console.log("qun")
				break;
			default:
				break;
		}
	});
	socketTask.onClose((res) => {
		console.log(res, "socket断开");
		//连接正常关闭
		store.state.isOpenSocket = false;
		//防止连接时出错重复重连函数执行
		if (!ws.isErrorTriggered) {
			reconnect();
		}
		ws.isErrorTriggered = false
	});

	ws.socketTask = socketTask;
}

// 心跳
function heartBeat() {
	let msg = {
		"code": "0"
	}
	heartBeatInterval = setInterval(() => {
		send(JSON.stringify(msg));
	}, heartBeatDelay)
}

/* 发送信息 */
function saveMessage(data) {
	//保存信息
	store.commit("m_message/saveMessageStorage", data)
}

// 发送消息
function send(value) {
	ws.socketTask.send({
		data: value,
		async success() {
			// console.log("消息发送成功", value)
		}
	});
}

// 重连
function reconnect() {
	clearInterval(heartBeatInterval);
	clearInterval(reconnectInterval);

	if (!store.state.isOpenSocket && !ws.isUserClose) {
		reconnectInterval = setInterval(() => {
			console.log("正在尝试重连")
			init();
		}, reconnectTimes)
	}
}

function completeClose() {
	//先将心跳与重连的定时器清除
	clearInterval(heartBeatInterval)
	clearInterval(reconnectInterval)

	ws.isUserClose = true;
	store.state.isOpenSocket = true;
	if (socketTask != null || socketTask != undefined) {
		console.log("退出成功关闭ws");
		ws.socketTask.close()
	}
	console.log("退出成功关闭ws");
}

export default ws